<template>
  <div class="room-module">
    <div class="room-header">
      <font-awesome-icon :icon="['fas', 'comments']"/>
      房间列表
    </div>
    <input v-model="searchQuery" type="text" class="room-search" placeholder="请输入房间名称" name="searchQuery"/>
    <div class="room-list">
      <div v-for="room in roomList" :key="room.id" class="room-item">
        <div class="room-item-up">
          <div class="room-item-image">
            <img :src="room.image || 'http://110.40.229.202//api/pms/images/18952334-4f0c-442a-ae7d-911949fd1895.jpg' "
                 alt="">
          </div>
          <div class="room-item-name">
            <div class="room-item-name-text">
              {{ room.name }}
            </div>
            <div class="room-item-name-desc">
              {{ room.description }}
            </div>
          </div>
          <div class="room-item-controls">
            <div class="room-item-join">
              <font-awesome-icon :icon="['fas', 'fa-sign-in-alt']" @click="joinRoom(room)"/>
            </div>
          </div>
        </div>
        <div class="room-item-down">
          <div class="room-type">
            <font-awesome-icon :icon="['fas', 'house-lock']" style="color: #e6a23c" v-if="room.type === 2"/>
            <font-awesome-icon :icon="['fas', 'house']" style="color: #409eff" v-else/>
          </div>
          <div class="room-time">
            {{ room.relativeTime }}
          </div>
          <div class="room-operation">
            <div class="room-dismiss">
              <font-awesome-icon :icon="['fas', 'fa-trash-can']" @click="dismissRoom(room.id)"
                                 style="color: #f56c6c;cursor: pointer;" v-if="room.ownerId === user.id"/>
            </div>
            <div class="room-edit">
              <font-awesome-icon :icon="['fas', 'pen-to-square']" @click="openEditRoomDialog(room.id)"
                                 style="color: #409eff;cursor: pointer;" v-if="room.ownerId === user.id"/>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="room-footer">
      <el-pagination
          style="float: right;"
          background
          :small="true"
          @size-change="handleSizeChange"
          @current-change="queryRoomList"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size"
          :layout="layout"
          :total="total">
        />
      </el-pagination>
    </div>
    <div class="room-bottom">
      <div class="room-button-all">
        <font-awesome-icon @click="queryPublicRoomList(1 , 10)"
                           :style="{color: activeButton === buttonStyle.all ? '#ffffff' : '#555555'}"
                           :icon="['fas', 'house-chimney']"/>
      </div>
      <div class="room-button-owner">
        <font-awesome-icon @click="queryOwnerRoomList(1, 10)"
                           :style="{color: activeButton === buttonStyle.owner ? '#ffffff' : '#555555'}"
                           :icon="['fas', 'house-chimney-user']"/>
      </div>
      <div class="room-button-create">
        <font-awesome-icon
                          @click="openCreateRoomDialog"
                          :style="{color: activeButton === buttonStyle.create ? '#ffffff' : '#555555'}"
                          :icon="['fas', 'house-chimney-medical']"/>
      </div>
    </div>
    <RoomPassDialog ref="roomPassDialog" :confirmRoomPass="confirmRoomPass"/>
    <RoomCreateDialog ref="roomCreateDialog" :createRoom="createRoom"/>
    <RoomEditDialog ref="roomEditDialog" :editRoom="editRoom"/>
  </div>
</template>

<script>
import {
  dismissRoom,
  queryOwnerRoomList,
  queryPublicRoomList,
  queryRoomById,
  verifyPassword,
  createRoom,
  editRoom
} from '@/api/http/room'
import RoomPassDialog from '@/components/dialog/RoomPassDialog.vue'
import RoomCreateDialog from "@/components/dialog/RoomCreateDialog.vue";
import RoomEditDialog from "@/components/dialog/RoomEditDialog.vue";

export default {
  name: "Room",
  components: {
    RoomCreateDialog,
    RoomPassDialog,
    RoomEditDialog
  },
  props: {
    user: {
      type: Object,
      default: () => {
      }
    },
    callGroupChat: {
      type: Function,
    },
    confirmHangup: {
      type: Function
    }
  },
  data() {
    return {
      roomList: [],
      searchQuery: "",
      currentPage: 1,
      size: 10,
      total: 0,
      layout: "prev , pager , next , jumper",
      timer: null,
      activeButton: 'all',
      buttonStyle: {
        all: 'all',
        owner: 'owner',
        create: 'create'
      }
    }
  },
  methods: {
    async queryPublicRoomList(currentPage = 1, size = 10) {
      this.activeButton = this.buttonStyle.all
      let result = await queryPublicRoomList({
        current: currentPage,
        size: size,
        name: this.searchQuery
      })
      if (result && result.code === 0) {
        this.roomList = result.data.records.map(room => ({
          ...room,
          relativeTime: this.formatRelativeTime(room.createTime)
        }));
        this.total = result.data.total;
        this.startRefreshTimer();
      }
    },
    async queryOwnerRoomList(currentPage = 1, size = 10) {
      this.activeButton = this.buttonStyle.owner
      let result = await queryOwnerRoomList({
        current: currentPage,
        size: size,
        name: this.searchQuery
      })
      if (result && result.code === 0) {
        this.roomList = result.data.records.map(room => ({
          ...room,
          relativeTime: this.formatRelativeTime(room.createTime)
        }));
        this.total = result.data.total;
        this.startRefreshTimer();
      }
    },
    handleSizeChange(pageSize) {
      this.size = pageSize
    },
    async queryRoomList(currentPage = 1) {
      this.currentPage = currentPage;
      if (this.activeButton === this.buttonStyle.all) {
        await this.queryPublicRoomList(this.currentPage, this.size);
      } else if (this.activeButton === this.buttonStyle.owner) {
        await this.queryOwnerRoomList(this.currentPage, this.size);
      }
    },
    startRefreshTimer() {
      // 清除可能存在的旧定时器
      this.stopRefreshTimer();
      // 创建新定时器
      this.timer = setInterval(() => {
        this.roomList.forEach(room => {
          room.relativeTime = this.formatRelativeTime(room.createTime)
        })
      }, 1000);
    },

    // 新增：停止定时器方法
    stopRefreshTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    async dismissRoom(roomId) {
      let result = await dismissRoom(roomId);
      if (result.code === 0) {
        this.$message.info('解散房间成功')
      } else {
        this.$message.error(result.msg)
      }
      await this.queryRoomList(this.currentPage)
    },
    formatRelativeTime(createTime) {
      const now = new Date();
      const create = new Date(createTime);
      const diffInSeconds = Math.floor((now - create) / 1000);

      // 计算时分秒
      const hours = Math.floor(diffInSeconds / 3600);
      const minutes = Math.floor((diffInSeconds % 3600) / 60);
      const seconds = diffInSeconds % 60;

      // 补零格式化
      const format = (num) => num.toString().padStart(2, '0');
      return `${format(hours)}:${format(minutes)}:${format(seconds)}`;
    },

    async joinRoom(room) {
      if (!(await this.confirmHangup())) {
        return
      }
      // 私密房间,且非房主时
      if (room.type === 2 && room.ownerId !== this.user.id) {
        this.$refs.roomPassDialog.show(room);
        return;
      }
      await this.startCallGroupChat(room.id);
    },
    // 通过密码加入房间
    async confirmRoomPass(room, password) {
      let result = await verifyPassword({
        id: room.id,
        password: password
      })
      let succ = result.code === 0
      if (succ) {
        await this.startCallGroupChat(room.id)
      } else {
        this.$message.error('密码输入错误');
      }
      return succ;
    },

    async startCallGroupChat(roomId) {
      const result = await queryRoomById(roomId);
      if (result.code === 0) {
        this.callGroupChat(result.data, this.user);
      } else {
        this.$message.error(result.msg)
      }
    },
    openCreateRoomDialog() {
      this.$refs.roomCreateDialog.openDialog();
    },
   async openEditRoomDialog(roomId){
      const result = await queryRoomById(roomId);
      if (result.code === 0){
        this.$refs.roomEditDialog.openDialog(result.data);
      }else{
        this.$message.error(result.msg)
      }
    },
    async createRoom(data){
      // TODO 上传图片
      const result = await createRoom(data)
      if (result.code !== 0){
        this.$message.error(result.msg)
        return
      }
      this.$message.success('新增房间成功');
      await this.queryOwnerRoomList();
    },
    async editRoom(data){
      const result = await editRoom(data)
      if (result.code !== 0){
        this.$message.error(result.msg)
        return
      }
      this.$message.success('编辑房间成功');
      await this.queryRoomList();
    }
  },
  mounted() {
    this.queryPublicRoomList();
  },
  beforeDestroy() {
    this.stopRefreshTimer();
  },
  watch: {
    // 搜索词变化时重置分页并重新加载
    searchQuery() {
      this.queryRoomList(1)
    }
  },
}
</script>

<style scoped>

.room-module {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1.2rem 0.6rem;
  gap: 0.6rem;
  min-height: 0;
  box-sizing: border-box;
  overflow: hidden;
}

.room-header {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  font-size: 1.1rem;
  font-weight: bold;
  color: #fff;
  margin-bottom: 0.5rem;
}

/* 新增搜索输入框样式 */
.room-search {
  /* 确保包含内边距和边框的总宽度不超出容器 */
  box-sizing: border-box;
  width: 100%;
  padding: 0.35rem 0.6rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 0.25rem;
  font-size: 0.9rem;
  background-color: #333;
  color: #fff;
  outline: none;
}

.room-list {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
  overflow-y: auto; /* 3. 内容溢出时显示内部滚动条 */
  /* 添加内边距补偿，避免内容紧贴滚动条 */
  padding-right: 8px;
  height: 80%; /* 减去头部和搜索框高度 */
}

.room-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0.1rem;
  border-radius: 0.4rem;
  background-color: rgba(255, 255, 255, 0.05);
  transition: background-color 0.3s ease;
  height: 100px;
  flex-shrink: 0;
}

.room-item-up {
  height: 70%;
  width: 100%;
  border-radius: 0.4rem 0.4rem 0 0;
  display: flex;
  flex-direction: row;
}

.room-item-image {
  width: 20%;
  height: 100%;
  justify-content: center;
  align-content: center;
  overflow: hidden;
}

.room-item-image img {
  width: 50%;
  height: 50%;
  border-radius: 50%;
  margin-left: 10px;
  object-fit: cover;
}

.room-item-name {
  width: 50%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.room-item-name-text {
  font-size: 1rem;
  color: #fff;
  margin-top: 0.5rem;
  justify-content: center;
  align-items: center;
}

.room-item-name-desc {
  font-size: 0.7rem;
  color: #fff;
  margin-top: 0.5rem;
}


.room-item-controls {
  width: 30%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: right;
  font-size: 20px;
  color: #fff;
  gap: 5px;
}

.room-item-join {
  height: 50%;
  width: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  cursor: pointer;
  margin-top: 2px;
}

.room-item-down {
  height: 30%;
  width: 100%;
  background-color: #444444;
  display: flex;
  flex-direction: row;
}

.room-type {
  font-size: 1rem;
  color: #fff;
  width: 10%;
  height: 100%;
  margin-left: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.room-time {
  font-size: 0.75rem;
  color: #fff;
  width: 70%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  margin-left: 10px;
}

.room-operation {
  display: flex;
  flex-direction: row;
  font-size: 0.9rem;
  color: #fff;
  width: 30%;
  height: 100%;
  align-content: center;
  justify-content: center;
  gap: 7px;
}

.room-operation > div {
  height: 100%;
  width: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  cursor: pointer;
}

.room-bottom {
  width: 100%;
  height: 4%;
  display: flex;
  flex-direction: row;
  gap: 2.5rem;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}

.room-bottom > div {
  width: 25%;
  height: 60%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 0.3rem;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 18px;
  color: #555555;
}


.room-button-all:hover,
.room-button-owner:hover,
.room-button-create:hover {
  opacity: 0.9;
  transform: scale(1.1);
}
</style>